package top.ivansong92.example.leetcode.learning.data.struct.linklist.extension;

public class NewLinkedListV2<E> {

    private Node dummyHead;
    private int size;

    public NewLinkedListV2() {
        dummyHead = new Node();
        size = 0;
    }


    public void addFirst(E e) {
        add(e, 0);
    }


    public void add(E e) {
        addLast(e);
    }

    public void addLast(E e) {
        add(e, size);
    }

    public void add(E e, int index) {
        if (index < 0 || index > size) {
            throw new IllegalArgumentException("index is illegal");
        }

        if (index == 0) {
            addFirst(e);
            return;
        }

        Node prev = dummyHead;
        for (int i = 0; i < index; i++) {
            prev = prev.next;
        }
        prev.next = new Node(e, prev.next);
        size++;
    }

    public E getFirst() {
        return get(0);
    }

    public E getLast() {
        return get(size - 1);
    }

    public E get(int index) {
        if (index < 0 || index >= size) {
            throw new IllegalArgumentException("index is illegal");
        }
        Node cur = dummyHead.next;
        for (int i = 0; i < index; i++) {
            cur = cur.next;
        }
        return (E) cur.e;
    }


    public E remove(int index) {
        if (index < 0 || index > size) {
            throw new IllegalArgumentException("index is illegal");
        }
        Node pre = dummyHead;
        for (int i = 0; i < index; i++) {
            pre = dummyHead.next;
        }
        Node cur = pre.next;
        pre.next = cur.next;
        cur.next = null;
        size--;
        return (E) cur.e;
    }


    public E removeFirst() {
        return remove(0);
    }

    public E removeLast() {
        return remove(size - 1);
    }

    public boolean isEmpty() {
        return size == 0;
    }

    public int size() {
        return size;
    }


    private static class Node<E> {
        public E e;
        public Node next;

        public Node(E e, Node next) {
            this.e = e;
            this.next = next;
        }


        public Node(E e) {
            this(e, null);
        }

        public Node() {
            this(null, null);
        }
    }
}
